package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "time"
)

var logg *log.Logger

func someHandler() {
    ctx, cancel := context.WithCancel(context.Background())
    go doStuff(ctx)

//10秒后取消doStuff
    time.Sleep(10 * time.Second)
    cancel()

}

//每1秒work一下，同时会判断ctx是否被取消了，如果是就退出
func doStuff(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            fmt.Println("don")
            logg.Printf("done")
            return
        default:
            logg.Printf("work")
            time.Sleep(1 * time.Second)
        }
    }
}

func main() {
    logg = log.New(os.Stdout, "", log.Ltime)
    ctx, cancel := context.WithCancel(context.Background())
    go doStuff(ctx)
    //10秒后取消doStuff
    time.Sleep(10 * time.Second)
    cancel()
    logg.Printf("down")
}
